<?php

if(!defined('IN_SYS')) exit('Access Denied');

class article_controller extends admincp{
	public function __construct(){
		parent::__construct();
	}

	public function index(){
		$yuming_id = $this->currentYumingId;
		if(!$yuming_id){
			self::redirect("?m=yuming&a=select");
		}
		$where = array();
		$stitle = gp("stitle");
		if($stitle){
			$where[] = " c.title like '%$stitle%' ";
		}
		$where = empty($where)?"":"where ".join(" AND ", $where);
		$pg = new page("select c.* , y.title as classname from content_{$yuming_id} as c left join classlist as y on c.class = y.ename and y.yuming_id={$yuming_id} $where order by c.id desc");

		$list = $pg->get_list(20);
		$page = $pg->get_page(); 

		foreach($list as $key => $r){
			$list[$key]['url'] = "http://".$this->currentYuming['name']."/{$r['class']}/{$r['id']}.html";
		}
		require self::tpl('article');
	}

	public function add(){
		$yuming_id = $this->currentYumingId;
		if(!$yuming_id){
			self::redirect("?m=yuming&a=select");
		}

		$allyuming = $this->allyuming;
		unset($allyuming[$yuming_id]);

		$draft_file = DATA.'/cache/article_draft.php';
		if(IS_POST){
			$data = gp("ymid,title,class,flag,thumb,keyword,description,tags,ymid,diytime");
			$data['body'] = gp("body", false);
			// 正式发布
			if ($data['diytime']) {
				$time = strtotime($data['diytime']);
			}
			if (empty($time)){
				$time = time();
			}
			if(empty($data['title'])){
				self::json( array('status' => 0, 'errMsg' => '请填写文章标题'));
			}
			if(empty($data['body'])){
				self::json( array('status' => 0, 'errMsg' => '请填写文章正文'));
			}
			if (empty($data['class'])) {
				self::json( array('status' => 0, 'errMsg' => '请选择文章栏目'));
			}
			
			if (!empty($data['ymid']) && !empty($allyuming[ $data['ymid'] ])) {
				$yuming_id = $data['ymid'];
			}

			$classlist = $this->get_classlist($yuming_id);

			if(empty($classlist[ $data['class'] ])) {	//如果不存在栏目，随机栏目
				$classkeys = array_keys($classlist);
				$randkey = rand(0,count($classkeys));
				$data['class'] = $classkeys[$randkey];
			}

			db::query("insert into content_{$yuming_id} (title, class, flag, thumb, keyword, addtime, status, description ) 
				values ('$data[title]', '$data[class]', '$data[flag]', '$data[thumb]', '$data[keyword]', '$time', '1', '$data[description]')");
			
			$content_id = db::insert_id();

			//存入标签
			$this->insert_tags($data['tags'], $yuming_id, $content_id);

			//存入文章内容
			$data['body']= stripslashes($data['body']);
			if(ymcms::article_write($yuming_id, $content_id, $data['body'])){
				if(is_file($draft_file)){
					unlink($draft_file);
				}

				//一键发布


				self::json( array('status' => 1, 'msg' => '添加成功', 'redirect' => '?m=article&a=index'));
			}else{
				self::json( array('status' => 0, 'errMsg' => '文章保存失败'));
			}
		}else{
			$classlist = $this->get_classlist($yuming_id);
			
			if(is_file($draft_file)){
				$r = require $draft_file;
			}else{
				$r = false;
			}
			require self::tpl("article_edit");
		}
	}

	public function edit(){
		$yuming_id = $this->currentYumingId;
		if(!$yuming_id){
			self::redirect("?m=yuming&a=select");
		}
		$id = gp('id');
		$r = db::find("select * from content_{$yuming_id} where id='$id' ");
		$classlist = $this->get_classlist($yuming_id);
		if(IS_POST){
			
			$data = gp("title,class,flag,thumb,keyword,description,tags,diytime");
			$data['body'] =  gp("body",false);
			if ($data['diytime']) {
				$time = strtotime($data['diytime']);
			}
			if (empty($time)){
				$time = $r['addtime'];
			}

			if(empty($data['title'])){
				self::json( array('status' => 0, 'errMsg' => '请填写文章标题'));
			}
			if(empty($data['body'])){
				self::json( array('status' => 0, 'errMsg' => '请填写文章正文'));
			}
			if (empty($data['class'])) {
				self::json( array('status' => 0, 'errMsg' => '请选择文章栏目'));
			}
			//存入标签
			$this->insert_tags($data['tags'], $yuming_id, $r['id']);

			$status = isset($_POST['savebtn'])?1:0;
			
			db::query("update content_{$yuming_id} set title='$data[title]', class='$data[class]', flag='$data[flag]', thumb='$data[thumb]', keyword='$data[keyword]',description='$data[description]',addtime='$time',status='$status' where id='$id' ");
			
			$data['body']= stripslashes($data['body']);
			if($data['body']){
				ymcms::article_write($yuming_id, $id,$data['body']);
			}
			self::json( array('status' => 1, 'msg' => '修改成功', 'redirect' => '?m=article&a=index'));

		}else{
			$res = db::select("select t.tagsname from tagindex_{$yuming_id} as i, tagslist_{$yuming_id} as t where i.tagid=t.id and i.aid='$id'");
			$arr_tags = array();
			foreach ($res as $v) {
				$arr_tags[] = $v['tagsname'];
			}
			$r['tags'] =join(",",$arr_tags);
			$r['body'] = ymcms::article_read($yuming_id, $r['id']);
			require self::tpl("article_edit");
		}
	}

	// 草稿自动保存
	public function draft(){
		$draft_file = DATA.'/cache/article_draft.php';
		$data = gp("title,class,flag,thumb,keyword,description,tags,ymids");
		$data['body'] = gp("body", false);
		$data['yuming_id'] = $this->currentYumingId;
		file_put_contents($draft_file, '<?php return '.var_export($data, true).';' );
		self::json( array('status' => 1, 'msg' => '自动保存成功'));
	}

	public function del(){
		$yuming_id = $this->currentYumingId;
		if(!$yuming_id){
			self::redirect("?m=yuming&a=select");
		}
		$id = gp('id');
		if(is_array($id)){
			foreach ($id as $v) {
				$this->del_handle($yuming_id, $v);
			}
		}else{
			$this->del_handle($yuming_id, $id);
		}
		self::redirect($_SERVER['HTTP_REFERER'], "删除成功");
	}

	private function del_handle($yuming_id, $id){
		ymcms::article_delete($id);
		db::query("delete from content_{$yuming_id} where id='$id' ");
	}

	private function insert_tags($tags, $yuming_id, $content_id){
		db::query("delete from tagindex_{$yuming_id} where aid='$content_id'");
		if(!empty($tags)){
			$time = time();
			$tags = preg_replace("#，#", ",", $tags);
			$tags = explode(",",$tags);
			$tagstr = implode("','", $tags);
			$res = db::select("select id,tagsname from tagslist_{$yuming_id} where tagsname in ('$tagstr') AND yuming_id='$yuming_id'");
			$oldtags = array();
			foreach ($res as $v) {
				$oldtags[] = $v['tagsname'];
			}
			foreach($tags as $key => $value){
				if(!in_array($value, $oldtags)) {
					db::query("insert into tagslist_{$yuming_id} (tagsname,addtime,yuming_id) values('$value', '$time','$yuming_id') ");
				}
			}
			db::query("insert into tagindex_{$yuming_id} (aid,tagid) select '$content_id',id from tagslist_{$yuming_id} where tagsname in ('$tagstr') AND yuming_id='$yuming_id'");
		}
	}

	private function get_classlist($yuming_id){
		$classlist = array();
		if($yuming_id) {
			$res = db::select("select c.* from classlist as c where c.status=1 and c.yuming_id='".$yuming_id."' order by c.weight,id");
			foreach ($res as $v) {
				$classlist[$v['ename']] = $v;
			}
		}
		return $classlist;
	}

}

